package top.namelessman.springbootjsp.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import top.namelessman.springbootjsp.entity.User;
import top.namelessman.springbootjsp.service.UserService;

@Controller
@RequestMapping("/user")
public class UserHandler {
    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("user/index");
        modelAndView.addObject("list",userService.findAll());
        return modelAndView;
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        userService.deleteById(id);
        return "redirect:/user/index";
    }

    @PostMapping("/add")
    public String add(Integer id,String name,String password){
        if(null==id||null==name||null==password){
            return "user/add";
        }
        userService.save(new User(id,name,password));
        return "redirect:/user/index";
    }

    @GetMapping("/update/{id}")
    public ModelAndView update(@PathVariable("id") Integer id){
        ModelAndView modelAndView = new ModelAndView("user/update");
        modelAndView.addObject("user",userService.findById(id));
        return modelAndView;
    }
    @PostMapping("/update/{id}")
    public String update(@PathVariable("id") Integer id,String name,String password){
        if(null==id||null==name||null==password){
            return "user/update";
        }
        userService.save(new User(id,name,password));
        return "redirect:/user/index";
    }

}
